//
//  ViedoPlayViewController.m
//  Leisure
//
//  Created by xalo on 16/7/5.
//  Copyright © 2016年 Hero. All rights reserved.
//

#import "ViedoPlayViewController.h"

@interface ViedoPlayViewController ()<UITableViewDataSource,UITableViewDelegate,PlayManagerDelegate>
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIWebView *webview;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UISlider *slide;
@property (weak, nonatomic) IBOutlet UIImageView *imageView;

@property (nonatomic,assign)NSInteger currentIndex;  //正在播放的下标
@property (nonatomic,strong)UIView *greenView;

@end

@implementation ViedoPlayViewController
//根据下标找到对应的cell
- (UITableViewCell *)fetchCellWithIndex:(NSInteger)index{
    
    return [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]];
}
//
- (UIView *)greenView{
    if (!_greenView) {
        _greenView = [[UIView alloc]initWithFrame:CGRectMake(kWidth-10, 0, 10, [self fetchCellWithIndex:0].frame.size.height)];
    }
    return _greenView;
}

//重写datasource的setter方法
- (void)setDataSource:(NSArray *)dataSource{
    if (_dataSource[0] != dataSource[0] ) {
        self.currentIndex = -1;
        _dataSource = dataSource;
    }
    
}

//控制器单例
+ (instancetype)sharedManager{
    static ViedoPlayViewController *handel = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        handel = [[ViedoPlayViewController alloc]initWithNibName:@"ViedoPlayViewController" bundle:nil];
    });
    return handel;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    
    //设置webview
    self.webview.backgroundColor = [UIColor clearColor];
    self.webview.opaque = NO;
    
    //防止一直播放同一首
    self.currentIndex = -1;
    //设置代理
    [PlayManager sharedManager].delegate = self;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//视图将要出现
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //为了防止点同一首歌重复播放
    if (self.index != self.currentIndex) {
        self.currentIndex = self.index;
        //调用设置信息方法
        [self setPlayInfoWithIndex:self.currentIndex];
    }

}


//快进快退
- (IBAction)slideAction:(UISlider *)sender {
    [[PlayManager sharedManager]playMusicWithSlideValue:sender.value];
}
//上一首
- (IBAction)playLastOne:(id)sender {
    if (self.currentIndex == 0) {
        self.currentIndex = self.dataSource.count-1;
    }else{
        self.currentIndex--;
    }
     [self setPlayInfoWithIndex:self.currentIndex];
}
//暂停/开始
- (IBAction)pause:(id)sender {
   
    if ([[PlayManager sharedManager] isPlaying] == 0) {
        [[PlayManager sharedManager] playMusic];
    }else{
        [[PlayManager sharedManager] pauseMusic];
    }

}
//下一首
- (IBAction)playNextOne:(id)sender {
    
    if (self.currentIndex == self.dataSource.count-1) {
        self.currentIndex = 0;
    }else{
        self.currentIndex++;
    }
    [self setPlayInfoWithIndex:self.currentIndex];
}
//设置界面信息
- (void)setPlayInfoWithIndex:(NSInteger)index{
    ViedoDetailModel *model = self.dataSource[index];
    //子线程加载信息，播放信息
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [[PlayManager sharedManager]prepareToPlayMusicWithUrl:model.musicURl];
        [self.webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:model.webview_url]]];
        
        
        //主线程刷新UI
        dispatch_async(dispatch_get_main_queue(), ^{
            self.title = model.title;
//            [self.coverimg sd_setImageWithUrl:[NSURL URLWithString:model.imgUrl]];
            
            [self.greenView removeFromSuperview];
            [[self  fetchCellWithIndex:index] addSubview:self.greenView];
            [self.tableView reloadData];
        });
    });
}



#pragma mark---------tableViewDelgate----------
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    
    cell.textLabel.text = [self.dataSource[indexPath.row] title];
    
    return cell;
}
#pragma mark--------PlayManagerDelegate--------
//传值
- (void)playManagerDelegateFetchTotalTime:(NSString *)totalTimer currentTime:(NSString *)currentTime progress:(CGFloat)progress{
    
    self.slide.value = progress;
}
//自动播放下一首
- (void)playToNextMusic{
    
    [self playNextOne:nil];
    
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
